//
//  HomeOrganizationalViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/4.
//  Copyright © 2016年 stone. All rights reserved.
//
#import "SNProductionPlanningViewController.h"
#import "SNOrganizationViewController.h"
#import "SNADView.h"
#import "AddModuleManager.h"
#import "ZXBuyNongjiViewController.h"
#import "ProductListTableViewController.h"
#import "FinanceLSViewController.h"
#import "ZXSTechnologyViewController.h"
#import "ZXBuyNongziViewController.h"
#import "HeZhuoSheViewController.h"
#import "ZuZhiViewController.h"
#import "DecisionMakerListViewController.h"
#import "HomeAddModuleViewController.h"
#import "HomeLSViewControllerSecond.h"
#import "SDCycleScrollView.h"
#import "HomeLSModel.h"
#import "HomeOrganizationalCell.h"
#import "HomeAddCell.h"
#import "DBModel.h"
#import <objc/runtime.h>
static NSMutableArray<DBModel *> * __models = nil;;
@interface HomeLSViewControllerSecond ()<SDCycleScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
/** View */
@property (weak, nonatomic) SNADView * adlView;
/** cycleScrollView */
@property (weak, nonatomic) SDCycleScrollView *cycleScrollView;
/** self.imageURLStrings */
@property (nonatomic,strong) NSMutableArray<NSString *> * imageURLStrings;
/** count */
@property (nonatomic,strong) NSNumber * countNumber;
/** NSMutableArray * imageNames */
@property (nonatomic,strong) NSMutableArray * imageNames;
/** View */
@property (weak, nonatomic) UICollectionView * collectionView;
/** HomeLSModel * homeLSModel */
@property (nonatomic,strong) HomeLSModel * homeLSModel;
/** amalgamateModels */
@property (nonatomic,strong) NSMutableArray<HomeLSResult *> * amalgamateModels;
/** otherModels */
@property (nonatomic,strong) NSMutableArray<HomeLSResult *> * otherModels;

/** firstload */
@property (nonatomic, assign,getter=isFirstload) BOOL firstload;
@end

@implementation HomeLSViewControllerSecond
- (void)updateCycleScrollView
{
    [[ZXHTTPManager sharedManager] getCycleViewDataCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        if (error) {
            NSLog(@"error = %@",error);
            return ;
        }
        NSLog(@"%@",jsonDict);
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        NSArray<NSDictionary *> * arr = jsonDict[@"result"];
        for(int i = 0; i < arr.count; i++) {
            NSDictionary * dict =  arr[i];
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",dict[@"resourceId"]];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            
            NSString * fileName = [NSString stringWithFormat:@"%02d.png",i];
            
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
            [imageNames addObject:kCachePath(fileName)];
        }
        
        self.cycleScrollView.imageURLStringsGroup = self.imageNames;
//      self.cycleScrollView.imageURLStringsGroup = @[
//                                                      @"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3215910746,2290723362&fm=21&gp=0.jpg",
//                                                      @"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3195266601,881181399&fm=21&gp=0.jpg"
//                                                      ];
        NSLog(@"self.imageNames = %@",self.imageNames);
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (self.firstload) {
        self.firstload = NO;
    }else{
        
        NSMutableArray * arrM = @[].mutableCopy;
        
        for (HomeAddModuleHomeconfigdomain * domain in [AddModuleManager sharedManager].homeAddModuleHomeconfigdomains) {
            
            HomeLSResult * obj = [HomeLSResult new];
            
            obj.linkUrl=domain.linkUrl;
            obj.ID=domain.ID;
            obj.role=domain.role;
            obj.sequence=domain.sequence;
            obj.isDefault=domain.isDefault;
            obj.resourceId=domain.resourceId;
            obj.resourceName=domain.resourceName;
            obj.linkDevice=domain.linkDevice;
            obj.title=domain.title;
            obj.subTitle=domain.subTitle;
            obj.titleColorString=domain.titleColorString;
            
            [arrM addObject:obj];
        }
        // [arrM addObjectsFromArray:self.otherModels];
        
        /** 排序 */
        NSComparator cmptr = ^(HomeLSResult * obj1, HomeLSResult* obj2){
            if ([obj1.sequence integerValue] > [obj2.sequence integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1.sequence integerValue] < [obj2.sequence integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        };
        
        
        NSMutableArray<HomeLSResult *> *array = [arrM sortedArrayUsingComparator:cmptr].mutableCopy;
        
        self.amalgamateModels = array;
        
        [self.collectionView reloadData];
    
    
        [self updateCycleScrollView];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDateADNotification" object:nil userInfo:nil];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.firstload = YES;
    [self addObserver:self forKeyPath:@"countNumber" options:NSKeyValueObservingOptionNew context:nil];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"首页";
    
    [self addCycleScrollView];
    
    [self addRequest];
    [self addCollectionView];
    [self addADView];
    
    [self.navigationController.navigationBar setBackgroundImage:[SNUtils imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[SNUtils imageWithColor:[UIColor clearColor]]];
}
- (void)addADView
{
    SNADView * adlView = ({
        CGFloat h = [UIScreen mainScreen].bounds.size.width * 3/7.0;
        SNADView * view = [[SNADView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - h-49 , [UIScreen mainScreen].bounds.size.width, h-49)];
        view.nav = (SNMYNavigationController *)self.navigationController;
        [self.view addSubview:view];
        
        //        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActived:)];
        //        [view addGestureRecognizer:tap];
        
        view;
    });
    self.adlView = adlView;
}
- (void)addRequest
{
    /** test */
//    [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:kUserInfo.USERID completed:^(NSDictionary *jsonDict, NSError *error) {
//        
//        logError;
//        
//        NSLog(@"%@",jsonDict);
//        
//    }];
    
    [[ZXHTTPManager sharedManager] getHomeConfWithCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        logError
        
        NSLog(@"%@",jsonDict);
        
        HomeLSModel * homeLSModel = [HomeLSModel mj_objectWithKeyValues:jsonDict];
        self.homeLSModel = homeLSModel;
        
        /** 排序 */
        NSComparator cmptr = ^(HomeLSResult * obj1, HomeLSResult* obj2){
            if ([obj1.sequence integerValue] > [obj2.sequence integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1.sequence integerValue] < [obj2.sequence integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        };
        
        NSMutableArray<HomeLSResult *> *arrM = [homeLSModel.result sortedArrayUsingComparator:cmptr].mutableCopy;
        
        self.amalgamateModels = arrM;
        
        //sn_note:=========  ============================ stone 🐳 ===========/
        
        
        self.otherModels = [NSMutableArray array];
        for (HomeLSResult * obj in self.homeLSModel.result) {
            //            if ([obj.title isEqualToString:@"生产计划"] || [obj.title isEqualToString:@"我的组织"]) {
            //                //
            //                [self.otherModels addObject:obj];
            //            }else{
            //买农资等...
            HomeAddModuleHomeconfigdomain * domain = [HomeAddModuleHomeconfigdomain new];
            
            domain.linkUrl = obj.linkUrl;
            domain.ID = obj.ID;
            domain.role = obj.role;
            domain.sequence = obj.sequence;
            domain.isDefault = obj.isDefault;
            domain.resourceId = obj.resourceId;
            domain.resourceName = obj.resourceName;
            domain.linkDevice = obj.linkDevice;
            domain.title = obj.title;
            domain.subTitle = obj.subTitle;
            domain.titleColorString = obj.titleColorString;
            
            [[AddModuleManager sharedManager].homeAddModuleHomeconfigdomains addObject:domain];
            //            }
        }
        
        [self.collectionView reloadData];
    }];
}
- (void)addCollectionView
{
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    /** 垂直方向 间距 */
    flowLayout.minimumLineSpacing = 10;
    /** 横向方向 间距 */
    flowLayout.minimumInteritemSpacing = 7.5;
    /** 内缩 内容 */
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 13, 10, 13);
    
    NSInteger colNum = 3;
    
    CGFloat w =  ([UIScreen mainScreen].bounds.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing * (colNum - 1)) / colNum;
    
    /** item大小 */
    flowLayout.itemSize = CGSizeMake(w,110);
    
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.cycleScrollView.frame), [UIScreen mainScreen].bounds.size.width, self.view.bounds.size.height - CGRectGetMaxY(self.cycleScrollView.frame)-49-64) collectionViewLayout:flowLayout];
    
    self.collectionView = collectionView;
    
    collectionView.backgroundColor = HexRGB(0xF5F5F5);
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [collectionView registerClass:[HomeOrganizationalCell class] forCellWithReuseIdentifier:@"HomeOrganizationalCell"];
    [collectionView registerClass:[HomeAddCell class] forCellWithReuseIdentifier:@"HomeAddCell"];
    [self.view addSubview:collectionView];
}
- (void)addCycleScrollView
{
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150) delegate:self placeholderImage:[SNUtils imageWithString:@"f5f5f5"]];
    self.cycleScrollView = cycleScrollView;
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [self.view addSubview:cycleScrollView];
    
    [[ZXHTTPManager sharedManager] getCycleViewDataCompleted:^(NSDictionary *jsonDict, NSError *error) {
        
        if (error) {
            NSLog(@"error = %@",error);
            return ;
        }
        NSLog(@"%@",jsonDict);
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        NSArray<NSDictionary *> * arr = jsonDict[@"result"];
        for(int i = 0; i < arr.count; i++) {
            NSDictionary * dict =  arr[i];
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",dict[@"resourceId"]];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                NSString * fileName = [NSString stringWithFormat:@"%02d.png",i];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                    [imageNames addObject:kCachePath(fileName)];
                    NSLog(@"fileName = %@",kCachePath(fileName));
                    self.countNumber = @(imageNames.count);
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"countNumber"]) {
        NSInteger count = [change[@"new"] integerValue];
        if(self.imageURLStrings.count == count){
            NSLog(@"change = %@",change[@"new"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.cycleScrollView.imageURLStringsGroup = self.imageNames;
            });
            
            NSString * keyString = [NSString stringWithFormat:@"%@", self.observationInfo];
            if ([keyString containsString:@"countNumber"]) {
                NSLog(@"首页轮播图监听者...close");
                [self removeObserver:self forKeyPath:@"countNumber"];
            }
            // [self removeObserver:self forKeyPath:@"countNumber"];
        }
    }
}
#pragma mark - <UICollectionViewDataSource>
/** section 数量 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
/** item 数量 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.amalgamateModels.count+1;
    //    return 6;
}
/** UICollectionViewCell */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.item == self.amalgamateModels.count) {
        HomeAddCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeAddCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
        return cell;
    }
    HomeOrganizationalCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeOrganizationalCell" forIndexPath:indexPath];
    
    cell.model = self.amalgamateModels[indexPath.item];
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
}
#pragma mark - <UICollectionViewDelegate>
// 选中操作
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@ | %s",self.class,__func__);
    
    if (indexPath.item == self.amalgamateModels.count) {
        HomeAddModuleViewController * vc =   [[HomeAddModuleViewController alloc] init];
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    HomeOrganizationalCell * cell = (HomeOrganizationalCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    if(cell.model.subTitle == nil || [cell.model.subTitle isEqualToString:@""]){ //生产计划等
        
        if([cell.titleLabel.text isEqualToString:@"生产计划"]){
//            DecisionMakerListViewController *viewController = [[DecisionMakerListViewController alloc] initWithNibName:@"DecisionMakerListViewController" bundle:nil];
//            [self.navigationController pushViewController:viewController animated:YES];
            
            SNProductionPlanningViewController * vc = [SNProductionPlanningViewController new];
            
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }else if([cell.titleLabel.text isEqualToString:@"我的组织"]){
//            //联社
//            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"6"]) {
//                //                    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ZuzhiViewController" bundle:nil];
//                ZuZhiViewController *zzvc = [[ZuZhiViewController alloc]init];
//                [self.navigationController pushViewController:zzvc animated:YES];
//                return;
//                //合作社
//            }else if([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"7"]){
//                HeZhuoSheViewController *sylbVC = [[HeZhuoSheViewController alloc] init];
//                [self.navigationController pushViewController:sylbVC animated:YES];
//                return;
//            }
            
            SNOrganizationViewController * vc = [SNOrganizationViewController new];
            
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{ // 买农资等

        if([cell.titleLabel.text isEqualToString:@"买农资"]){
            ZXBuyNongziViewController *vc = [[ZXBuyNongziViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }else if([cell.titleLabel.text isEqualToString:@"学农技"]){
            ZXSTechnologyViewController *vc = [[ZXSTechnologyViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }else if([cell.titleLabel.text isEqualToString:@"投资理财"]){
            [self.navigationController pushViewController:[FinanceLSViewController new] animated:YES];
            return;
        }else if([cell.titleLabel.text isEqualToString:@"找贷款"]){
            ProductListTableViewController *viewController = [[ProductListTableViewController alloc] init];
            [self.navigationController pushViewController:viewController animated:YES];
            return;
        }else if([cell.titleLabel.text isEqualToString:@"找农机"]){
            ZXBuyNongjiViewController *vc = [[ZXBuyNongjiViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
}
// 取消选中操作
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@ | %s",self.class,__func__);
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    
    // [self.navigationController pushViewController:[NSClassFromString(@"DemoVCWithXib") new] animated:YES];
}
@end
